import { useEffect, useMemo, useRef, useState, type FormEvent } from 'react'
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate, useParams } from 'react-router-dom'
import dayjs from 'dayjs'
import ReactMarkdown from 'react-markdown'

import { DiaryAPI } from '../app/api'
import type { ApiDiaryComment } from '../app/types'
import PageHeader from '../components/PageHeader'
import Button from '../components/ui/Button'
import { Card } from '../components/ui/Card'
import { FormField, Input, Textarea } from '../components/ui/Form'
import useThemeStore from '../app/store/themeStore'
import DiaryComposerDialog from '../components/DiaryComposerDialog'
import { KebabMenu } from '../components/ui/Menu'

const COMMENT_PAGE_SIZE = 20

const DiaryDetailPage = () => {
  const { entryId } = useParams<{ entryId: string }>()
  const id = Number(entryId)
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const { data, isLoading } = useQuery({
    queryKey: ['diary', id, 'entry'],
    enabled: Number.isFinite(id),
    queryFn: () => DiaryAPI.getOne(id),
  })

  // 动态标题：日记标题 | 恋爱日记
  useEffect(() => {
    if (typeof document === 'undefined') return
    const base = '恋爱日记 · Love Notes'
    if (data?.title) document.title = `${data.title} · Love Notes`
    else document.title = base
  }, [data?.title])

  const commentsQuery = useInfiniteQuery({
    queryKey: ['diary', id, 'comments'],
    enabled: Number.isFinite(id),
    initialPageParam: 0,
    queryFn: ({ pageParam = 0 }) => DiaryAPI.listComments(id, { limit: COMMENT_PAGE_SIZE, offset: pageParam }),
    getNextPageParam: (lastPage) => lastPage.next_offset ?? undefined,
  })

  useEffect(() => {
    if (!data) return
    const initialItems = data.comments ?? []
    const nextOffset = data.comments_meta?.next_offset ?? null
    queryClient.setQueryData(['diary', id, 'comments'], {
      pages: [{ items: initialItems, next_offset: nextOffset }],
      pageParams: [0],
    })
  }, [data, id, queryClient])

  const comments = useMemo(
    () => commentsQuery.data?.pages.flatMap((page) => page.items) ?? [],
    [commentsQuery.data],
  )

  const [comment, setComment] = useState('')
  // 评论不再记录心情，仅文本
  const [editing, setEditing] = useState(false)
  const autoMode = useThemeStore((s) => s.autoMode)
  const setTheme = useThemeStore((s) => s.setMode)
  const commentsLoadMoreRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    const node = commentsLoadMoreRef.current
    if (!node) return
    const observer = new IntersectionObserver(
      (entries) => {
        const [entry] = entries
        if (entry?.isIntersecting && commentsQuery.hasNextPage && !commentsQuery.isFetchingNextPage) {
          commentsQuery.fetchNextPage()
        }
      },
      { rootMargin: '160px 0px 160px 0px' },
    )
    observer.observe(node)
    return () => observer.disconnect()
  }, [commentsQuery.fetchNextPage, commentsQuery.hasNextPage, commentsQuery.isFetchingNextPage])

  // Mood-driven theme
  const moodToTheme = (m?: string): 'soft' | 'vibrant' => {
    if (!m) return 'soft'
    const t = m.toLowerCase()
    const positive = ['开心', '喜', '乐', '激动', '兴奋', '幸福', '热情']
    const negatives = ['难过', '郁', '忧', '疲', '累', '无力', '低落']
    if (positive.some((k) => t.includes(k))) return 'vibrant'
    if (negatives.some((k) => t.includes(k))) return 'soft'
    return 'soft'
  }

  if (autoMode && data?.mood) {
    setTheme(moodToTheme(data.mood))
  }

  const addMutation = useMutation({
    mutationFn: (payload: { content: string }) => DiaryAPI.addComment(id, payload),
    onSuccess: async () => {
      setComment('')
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: ['diary', id, 'entry'] }),
        queryClient.invalidateQueries({ queryKey: ['diary', id, 'comments'] }),
      ])
    },
  })

  const removeMutation = useMutation({
    mutationFn: (commentId: number) => DiaryAPI.deleteComment(id, commentId),
    onSuccess: async () => {
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: ['diary', id, 'entry'] }),
        queryClient.invalidateQueries({ queryKey: ['diary', id, 'comments'] }),
      ])
    },
  })

  const tags = useMemo(() => (data?.tags ?? []).slice(0, 10), [data?.tags])

  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    if (!comment.trim() || addMutation.isPending) return
    addMutation.mutate({ content: comment.trim() })
  }

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Diary"
        title={data?.title ?? '日记详情'}
        description={data?.created_at ? dayjs(data.created_at).format('YYYY 年 MM 月 DD 日 HH:mm') : undefined}
        actions={
          <div className="flex items-center gap-2">
            <Button onClick={() => navigate(-1)} variant="secondary" size="sm">返回</Button>
            {data ? (
              <KebabMenu
                items={[
                  { label: '编辑', onSelect: () => setEditing(true) },
                  {
                    label: '删除', danger: true, onSelect: async () => {
                      await DiaryAPI.remove(id)
                      navigate('/diary', { replace: true })
                    }
                  },
                ]}
              />
            ) : null}
          </div>
        }
      />

      <div className="grid gap-6 lg:grid-cols-[1.1fr_0.9fr]">
        <Card title="正文" padding="lg">
          {isLoading ? (
            <p className="text-sm text-slate-400">加载中...</p>
          ) : (
            <ReactMarkdown className="markdown-body">{data?.content_md ?? data?.ai_summary ?? ''}</ReactMarkdown>
          )}
          {tags.length > 0 ? (
            <div className="mt-4 flex flex-wrap gap-2">
              {tags.map((tag) => (
                <span key={tag} className="badge">#{tag}</span>
              ))}
            </div>
          ) : null}
        </Card>

        {data?.ai_summary ? (
          <Card title="AI 摘要" description="由 AI 根据正文提炼，请结合原文理解" padding="lg">
            <p className="text-sm leading-relaxed text-slate-700">{data.ai_summary}</p>
          </Card>
        ) : null}

        <Card title="评论" description="和 TA 一起留下更完整的时刻" padding="lg">
          <form onSubmit={handleSubmit} className="space-y-3">
            <FormField label="想说的话">
              <Textarea value={comment} onChange={(e) => setComment(e.target.value)} placeholder="写下你的想法..." />
            </FormField>
            {/* 评论不再提供心情字段 */}
            <div className="flex justify-end">
              <Button type="submit" size="sm" disabled={!comment.trim() || addMutation.isPending}>
                {addMutation.isPending ? '发送中...' : '发送评论'}
              </Button>
            </div>
          </form>

          <div className="mt-6 space-y-3">
            {commentsQuery.isLoading && comments.length === 0 ? (
              <p className="text-sm text-slate-400">评论加载中...</p>
            ) : comments.length === 0 ? (
              <p className="text-sm text-slate-400">还没有评论，留下第一条吧。</p>
            ) : (
              comments.map((c: ApiDiaryComment) => (
                <article key={c.id} className="rounded-2xl border border-slate-100 bg-slate-50/70 p-4">
                  <div className="flex items-center justify-between">
                    <p className="text-sm font-semibold text-slate-900">{c.author_name ?? '用户'}</p>
                    <p className="text-xs text-slate-400">{c.created_at ? dayjs(c.created_at).format('MM-DD HH:mm') : ''}</p>
                  </div>
                  {/* 不显示评论心情 */}
                  <p className="mt-1 text-sm text-slate-700">{c.content}</p>
                  <div className="mt-2 flex justify-end">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => removeMutation.mutate(c.id)}
                    >
                      删除
                    </Button>
                  </div>
                </article>
              ))
            )}
            <div ref={commentsLoadMoreRef} className="h-4" />
            {commentsQuery.isFetchingNextPage ? (
              <p className="text-center text-xs text-slate-400">加载更多评论中...</p>
            ) : null}
            {!commentsQuery.hasNextPage && comments.length > 0 ? (
              <p className="text-center text-xs text-slate-300">没有更多评论了</p>
            ) : null}
          </div>
        </Card>
      </div>
      {data ? (
        <DiaryComposerDialog
          open={editing}
          onClose={() => setEditing(false)}
          entry={{
            id: id,
            title: data.title,
            content_md: data.content_md,
            mood: data.mood,
            tags: data.tags ?? [],
            visibility: data.visibility,
          }}
        />
      ) : null}
    </div>
  )
}

export default DiaryDetailPage
